(function () {

    /**
     * protocol：
     * - product: 产品隔离标识， 例如：git-helper
     * - domain:   活动类型， 例如：storage.local，标识对本地存储进行操作
     * - action:   标识活动， 例如：get，用于区分操作 
     * - data:     携带的数据， 例如：{project: 'qz_one2'}
     */
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        let product = request.product || '';
        let domain = request.domain || '';
        let action = request.action || '';
        let data = request.data || {};

        if (product === 'git-helper') {
            gitHelperStorage(getStorage(domain), action, data).then((re) => {
                sendResponse({ success: true, data: re });
            });
            // 返回 true 以指示将会异步调用 sendResponse
            return true;
        }

    });


    function getStorage(storageType) {
        // 获取存储对象
        return storageType === 'storage.sync' ? chrome.storage.sync : chrome.storage.local;
    }

    function baseStorage(storage, action, data) {

        return new Promise((resolve, reject) => {
            if (action === 'get') {
                storage.get(data, (re) => { resolve(re) });
            }
            else if (action === 'set') {
                storage.set(data, () => { resolve({ success: true }) });
            } else if (action === 'remove') {
                storage.remove(data, () => { resolve({ success: true }) });
            } else if (action === 'clear') {
                storage.clear(() => { resolve({ success: true }) });
            }
        })

    }
    
    async function gitHelperStorage(storage, action, data) {

        // 通用
        if (["get", "set", "renove", "clear"].includes(action)) {
            return await baseStorage(storage, action, data);
        // } else {
        //     return await gitHelperStorage1(storage, action, data);
        }

    }


    async function gitHelperStorage1(storage, action, data, sendResponse){
        return new Promise((resolve,reject)=>{
            //project
            if (action === 'getProjects') {
                storage.get('project', (re) => { sendResponse(re); });
                return true; // 表示异步响应
            } else if (action === 'setProjects') {
                storage.set({ project: data.project }, () => { sendResponse({}); });
                return true;
            } else if (action === 'removeProjects') {
                storage.remove("project", () => { sendResponse({}); });
                return true;
            }

            // categories
            else if (action === 'getCategories') {
                storage.get('categories', (data) => { sendResponse(data); });
                return true;
            } else if (action === 'setCategories') {
                storage.set({ categories: data.categories }, () => { sendResponse({}); });
                return true;
            } else if (action === 'removeCategories') {
                storage.remove("categories", () => { sendResponse({}); });
                return true;
            }

            // products
            else if (action === 'getProducts') {
                storage.get('products', (data) => { sendResponse(data); });
                return true;
            } else if (action === 'setProducts') {
                storage.set({ products: data.products }, () => { sendResponse({}); });
                return true;
            } else if (action === 'removeProducts') {
                storage.remove("products", () => { sendResponse({}); });
                return true;
            }

            // clear all
            else if (action === 'clear') {
                storage.clear(() => { sendResponse({}); });
                return true;
            }

            // invalid action
            else {
                sendResponse({ success: false, message: 'Invalid action' });
                return false;
            }
        })

    }


    /*

    1. 存储数据
    使用storage.set方法存储数据，该方法接受一个对象作为参数，对象的键值对表示要存储的数据。

    storage.set({'key1': 'value1', 'key2': 'value2'}, function() {
    console.log('Data stored successfully.');
    });

    2. 读取数据
    使用storage.get方法读取数据，该方法接受一个包含要读取的键的数组作为参数。

    storage.get(['key1', 'key2'], function(data) {
    console.log('Data loaded:', data);
    });

    3. 删除数据
    使用storage.remove方法删除指定数据，

    storage.remove('key1', function() {
    console.log('Key1 removed');
    });

    4. 使用storage.clear方法清空所有数据：

    storage.clear(function(){
    console.log('All local storage cleared');
    });

    5. 监听数据变化
    使用chrome.storage.onChanged.addListener监听数据变化：

    chrome.storage.onChanged.addListener((changes, namespace) => {
    for (let [key, {oldValue, newValue}] of Object.entries(changes)) {
        console.log(${key}: ${oldValue} -> ${newValue});
    }
    });

    */

})();